<template>
  <div class="mod-config">
    <el-button type="primary" @click="uploadPic();">添加PC安装包</el-button>
    <el-dialog title="添加PC安装包" :visible.sync="dialogFormVisible" :before-close="handleClose">
      <el-form ref="form" :model="form" label-width="120px" class="demo-ruleForm">
        <el-form-item label="安装包版本名称："
          prop="editionName"
          :rules="[{ required: true, message: '安装包版本名称不能为空'}]">
          <el-input
              type="name"
              placeholder="请输入内容"
              v-model="form.editionName"
              style="width: 50%"
              clearable>
            </el-input>
        </el-form-item>
        <el-form-item label="PC安装包："
          prop="pcsystemEdition"
          :rules="[{ required: true, message: 'PC安装包不能为空'}]">
          <el-upload
            class="upload-demo"
            :limit="1"
            drag
            action="http://121.41.167.195:8000/api/oss/upload"
            :file-list="fileList"
            :on-success="uploadSuccess"
            :on-exceed="uploadExceed"
            :on-remove="handleUploadRemove"
            :before-remove="beforeVodRemove"
            :before-upload="beforeTextUpload"
            >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <!-- <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div> -->
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="insertPcSystem();">保 存</el-button>
      </div>
    </el-dialog>
    <el-table
      :data="dataList"
      stripe
      v-loading="dataListLoading"
      style="width: 100%"
    >
      <el-table-column prop="id" label="系统版本id" width="180">
      </el-table-column>
      <el-table-column prop="editionName" label="版本名称" width="180">
      </el-table-column>
      <el-table-column prop="createtime" sortable label="创建时间"> </el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="150"
        label="操作"
      >
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            @click="deleteHandle(scope.row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页条 -->
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
    >
    </el-pagination>

  </div>
</template>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
<script>
export default {
  data() {
    return {
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dialogVisible: false,
      dialogFormVisible: false,
      form: {
          editionName: '',
          pcsystemEdition: '',
        },
      fileList: [],
    };
  },
  components: {},
  activated() {
    this.getDataList();
  },
  methods: {
    // 上传课本之前的钩子函数
    beforeTextUpload(file){
      const fileName = file.name;
      const fileType = fileName.substring(fileName.lastIndexOf("."));
      if (fileType !== ".exe") {
        this.$message.error("上传PC安装包只能是exe!");
        return false;
      }
      return true;
    },
    // 删除之前，就是点击x的时候
    beforeVodRemove(file) {
      return this.$confirm(`确定移除 ${file.editionName}？`);
    },
    // 点击确定的时候进行彻底删除
    handleUploadRemove() {
      this.form.pcsystemEdition = '';
      this.fileList = [];
    },
    //文件上传超出数量限制
    uploadExceed(){
      this.$message({
        message: '只能上传一个文件!',
        type: 'error'
      });
    },
    //文件上传成功
    uploadSuccess(response, file, fileList){
      this.fileList = [];
      let fileObj = {};
      let filenamelist = response.url.toString().split("/");
      fileObj['name'] = filenamelist[filenamelist.length-1];
      fileObj['url'] = response.url;
      this.fileList.push(fileObj);
      this.form.pcsystemEdition = response.url;
    },
    //上传按钮事件
    uploadPic() {
      this.dialogFormVisible = true;
    },
    //存硬笔系统记录
    insertPcSystem(){
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl("/sf/cbpcsystemedition/save"),
            method: "post",
            data: this.$http.adornParams({
              editionName: this.form.editionName,
              pcsystemEdition: this.form.pcsystemEdition,
            }),
          }).then(({ data }) => {
            this.form.editionName = '';
            this.form.pcsystemEdition = '';
            this.fileList = [];
            this.dialogFormVisible = false;
            this.$message({
              message: '添加成功!',
              type: 'success'
            });
            this.getDataList();
          });
        }else{
          this.$message.error('PC系统版本名称不能为空或安装包未上传！');
        }
      });
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          this.form.editionName = '';
          this.form.pcsystemEdition = '';
          this.fileList = [];
          done();
        })
        .catch(_ => {});
    },
    // 获取安装包分页数据
    getDataList() {
      this.dataListLoading = true;
      this.$http({
        url: this.$http.adornUrl("/sf/cbpcsystemedition/list"),
        method: "get",
        params: this.$http.adornParams({
          page: this.pageIndex,
          limit: this.pageSize,
        }),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.dataList = data.pcsystemEditionPage.records;
          this.totalPage = data.pcsystemEditionPage.total;
        } else {
          this.dataList = [];
          this.totalPage = 0;
        }
        this.dataListLoading = false;
      });
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.pageIndex = 1;
      this.getDataList();
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val;
      this.getDataList();
    },
    // 删除
    deleteHandle(editionId) {
      this.$confirm(`确定对[PC安装包id=${editionId}]进行[删除]操作?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
          this.$http({
            url: this.$http.adornUrl("/sf/cbpcsystemedition/delete"),
            method: "post",
            data: this.$http.adornData([editionId], false),
          }).then(({ data }) => {
            console.log(data);
            if (data && data.code === 0) {
              this.$message({
                message: "删除成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.getDataList();
                },
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        })
        .catch(() => {});
    },
  },
};
</script>